using System;
using System.Text.RegularExpressions;
using System.Web;

using Swaf;
using Swaf.BizObj;

namespace StarterSite
{
	public class SiteGlobal : Swaf.Gui.AspNet2.AspNetGlobal
	{
		protected static Regex s_rss = new Regex(@"(.*?)/rss/([^/]+?)\.aspx$", RegexOptions.IgnoreCase);
		protected static Regex s_articleOnly = new Regex(@"(.*?)/articles/([^/]+?)\.aspx$", RegexOptions.IgnoreCase);
		protected static Regex s_articleWithPid = new Regex(@"(.*?)/articles/([^_]+?)_([^/]*?)\.aspx$", RegexOptions.IgnoreCase);
		protected static Regex s_productOnly = new Regex(@"(.*?)/products/([^/]+?)\.aspx$", RegexOptions.IgnoreCase);
		protected static Regex s_productWithPid = new Regex(@"(.*?)/products/([^/]+?)_([^/]+?)\.aspx$", RegexOptions.IgnoreCase);
		protected static Regex s_companyNameUrl = new Regex(@"[^.]*\.([^.]+)\.", RegexOptions.IgnoreCase);

		public string AppConfigFileName { get { return @"\configFiles\StarterSiteWebApplication.xml"; } }

		public void Application_AuthorizeRequest(object sender, EventArgs e)
		{
			HttpContext incoming = HttpContext.Current;
			string oldpath = incoming.Request.Path;
			string newPath = oldpath;
			string companyId = null;
			// Regular expressions to grab the page id from the pageX.aspx 
			Match m;
			if (string.Compare(oldpath, "/articles/login.aspx", true) == 0)
				newPath = "/std/login.aspx";
			else if ((m = s_articleWithPid.Match(oldpath)).Success)
				newPath = string.Format("{0}/std/ArticleView.aspx?gArt1pid={1}&gArt1id={2}", !Cmn.IsEmpty(companyId) ? companyId : m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value);
			else if ((m = s_articleOnly.Match(oldpath)).Success)
				newPath = string.Format("{0}/std/ArticleView.aspx?gArt1pid={1}&gArt1id={1}", !Cmn.IsEmpty(companyId) ? companyId : m.Groups[1].Value, m.Groups[2].Value);
			else if ((m = s_productOnly.Match(oldpath)).Success)
				newPath = string.Format("{0}/std/ProductView.aspx?pArt1pid={1}&pArt1id={1}", !Cmn.IsEmpty(companyId) ? companyId : m.Groups[1].Value, m.Groups[2].Value);
			else if ((m = s_productWithPid.Match(oldpath)).Success)
				newPath = string.Format("{0}/std/ProductView.aspx?pArt1pid={1}&pArt1id={2}", !Cmn.IsEmpty(companyId) ? companyId : m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value);
			else if ((m = s_rss.Match(oldpath)).Success)
				newPath = string.Format("{0}/std/Rss.aspx?id={1}", m.Groups[1].Value, m.Groups[2].Value);
			else if (!Cmn.IsEmpty(companyId) && !oldpath.StartsWith(companyId))
				newPath = companyId + oldpath;

			incoming.RewritePath(newPath, true);
		}
	}

}
	

